# This code is part of cqlib.
#
# Copyright (C) 2025 China Telecom Quantum Group, QuantumCTek Co., Ltd.,
# Center for Excellence in Quantum Information and Quantum Physics.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

import os
import pytest
from cqlib.quantum_platform import TianYanPlatform
from cqlib import Circuit
from cqlib.mapping import transpile_qcis

LOGIN_KEY = os.getenv("LOGIN_KEY")
MACHINE_NAME = os.getenv("TIANYAN_MACHINE", "tianyan504")


@pytest.fixture(scope="session")
def platform():
    assert LOGIN_KEY, "Please set env var LOGIN_KEY"
    assert MACHINE_NAME, "Please set env var TIANYAN_MACHINE (or rely on default)."
    return TianYanPlatform(login_key=LOGIN_KEY, machine_name=MACHINE_NAME)


def build_demo_qcis() -> str:
    c = Circuit(8)
    c.h(0)
    c.s(1)
    c.sd(2)
    c.rx(1, 1)
    c.ry(2, 1)
    c.rz(3, 1)
    c.t(3)
    c.td(3)
    for q in range(c.num_qubits):
        if q != 0:
            c.cx(q, 0)

    c.h(0)
    c.s(1)
    c.sd(2)
    c.rx(1, 1)
    c.ry(2, 1)
    c.rz(3, 1)
    c.t(3)
    c.td(3)
    for q in range(c.num_qubits):
        if q != 1:
            c.cx(q, 1)

    c.measure_all()
    return c.qcis


def test_tianyan_transpile_smoke(platform):
    qcis_before = build_demo_qcis()
    assert qcis_before and qcis_before.strip(), "Empty QCIS from original circuit"

    new_circuit, initial_layout, swap_mapping, mapping_virtual_to_final = transpile_qcis(qcis_before, platform)

    # 结果最小断言（不做 isinstance）
    assert new_circuit, "Transpiler returned empty new_circuit"
    qcis_after = getattr(new_circuit, "qcis", "")
    assert qcis_after and qcis_after.strip(), "Empty QCIS after mapping"

    assert initial_layout is not None, "initial_layout is None"
    assert swap_mapping is not None, "swap_mapping is None"
    assert mapping_virtual_to_final is not None, "mapping_virtual_to_final is None"

    # 可选规则检查（平台若支持）
    if hasattr(platform, "qcis_check_regular"):
        assert platform.qcis_check_regular(qcis_after.upper()), "QCIS regular check failed"